<template>
  <div class="box">
      <input type="checkbox" name="" :id="id" :checked="initCheck(isCheck)" @change="amend(isCheck)">
      <label :for="id">
        <img :src="image" :alt="typeOf">
      </label>
      <div class="goodsInfo">
        <span>{{name}}</span>
        <div style="display: flex;width: 100%;justify-content: space-between;">
          <span>{{price}}<em style="font-size: 12px; color: red;">￥</em></span>
          <span><button @click="alert('reduce')">-1</button> {{count}} <button @click="alert('add')">+1</button></span>
        </div>
      </div>
  </div>
</template>

<script>
export default {
  props: {
    price: {
      default: 0,
      type: Number,
    },
    typeOf: {},
    name: {
      type: String,
      default: ''
    },
    isCheck: {
      type: Number,
      default: 0
    },
    id: {
      required: true,
      type: Number,
    },
    image: {
      type: String,
    },
    count: {
      default: 0,
      type: Number
    }
  },
  emits: ['updateCount', 'updateIsCheck'],
  mounted() {
    
  },
  computed: {
    initCheck() {
      return function(val) {
        // console.log(val)
        let check
        if(val) return check = true
        check = false
        return check
      }
    }
  },
  methods: {
    alert(val) {
      if(val === 'reduce') {
        if(this.count <= 1) return  // 商品数量最少为 1, 当商品数量为 1 时，退出当前事件
        this.$emit('updateCount', [this.count - 1, this.id])
      } else {
        this.$emit('updateCount', [this.count + 1, this.id])
      }
      
    },
    
    amend(check) {
      // 当选择的状态为 1, 时, 将返回未选中的状态
      if(check === 1) return this.$emit('updateIsCheck', [0, this.id])
      // 否则返回选中的状态
      this.$emit('updateIsCheck', [1, this.id])
    }
  }
}
</script>

<style scoped>
  .box {
    width: 100%;
    height: 100px;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 10px;
    margin-bottom: 10px;;
  }
  .goodsInfo{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 10px;
  }
  img {
    width: 100px;
    height: 100px;
    border-radius: 10px;
  }
</style>